import React, { FC, useEffect, useState } from 'react'
import { Form, Input, Button, Select, Row, Col, DatePicker, Modal } from 'antd'
import { itemList, itemForExcel, queryTrajectory } from '~/api/query-api'
import ItemClassification from '~/components/item-classification'
import TrajectoryModal from './container/trajectory-modal'
import { WhereaboutsItemsMap, TaskItemMap, CustodyState, AcqueryWayMap } from '~/constants'
import moment from 'moment'
import useGetMembers from '~/hooks/useGetMembers'
import useGetDepartMents from '~/hooks/useGetDepartMents'
export const contextPath = process.env.NODE_ENV === 'production' ? '/portal' : '' //'/portal' 对应后台的 springboot 的contextPath
import MoveList from './container/moved-list'
import ItemModal from '~/components/item-modal'
import { Spin } from 'antd'
const cacheRecord: any = {}
const localStorageAuth = JSON.parse(localStorage.getItem('u')!)?.roles[0]

const { Option } = Select
const { RangePicker } = DatePicker
const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 }
}
const formWidth = 400

const Home: FC = () => {
  // const uuid = new Date().getTime()
  const [form] = Form.useForm()
  const [moveList, setMoveList] = useState([])
  const [trajectoryVisible, setTrajectoryVisible] = useState(false)
  const [listData, setListData] = useState([])
  const [record, setRecord] = useState({})
  const departMents = useGetDepartMents()
  const [departmentCode, setDepartmentCode] = useState(
    localStorage.getItem('u') ? JSON.parse(localStorage.getItem('u')!).departmentCode : ''
  )
  const receiveMembers = useGetMembers(departmentCode)

  const { resetFields } = form

  const handleGetQueryWaitList = async (params: any) => {
    const { caseNo, itemClassification, createTime, measureTime, acquireTime, itemName } = params

    if (localStorageAuth === 'STOREMAN' && !caseNo && !createTime && !measureTime) {
      alert('请输入案件编号或采集时间或实际执行时间进行查询！！')
      return
    }

    if (localStorageAuth === 'KEEPER' && !caseNo && !createTime && !measureTime) {
      alert('请输入案件编号或采集时间或实际执行时间进行查询！！')
      return
    }
    if (acquireTime && createTime) {
      alert('采集时间和实际执行时间不能同时输入;')
      return
    }

    const uuid2 = new Date().getTime()
    setVisible(true)
    const { data } = await itemList({
      ...params,
      itemName: itemName ? itemName : null,
      filename: uuid2,
      needItemOnlineStatus: true,
      createEndTime: createTime && moment(createTime[1]).format(),
      createStartTime: createTime && moment(createTime[0]).format(),
      measureEndTime: measureTime && moment(measureTime[1]).format(),
      measureStartTime: measureTime && moment(measureTime[0]).format(),
      categoryId1: itemClassification && itemClassification[0],
      categoryId2: itemClassification && itemClassification[1],
      categoryId3: itemClassification && itemClassification[2],
      itemQueryOrder: acquireTime ? 'REAL_GET_TIME_DESC' : 'ACQUIRE_TIME_DESC'
    })

    setMoveList(data)
    setVisible(false)
  }

  const getExcel = (val: any) => {
    if (Array.isArray(val)) {
      if (val.length === 0) {
        alert('没有查询结果！')
        return
      }
      val.map((item, index) => {
        if (index === 0) {
          // alert(item.filename)
          // window.open("http://15.75.21.19:9081/api/v1/item/item/exportItem?caseNo="+item.filename)
          window.open('http://15.75.10.165:9081/api/v1/item/item/exportItem?caseNo=' + item.filename)
        }
      })
    }
  }

  const onFinish = (val: any) => {
    handleGetQueryWaitList(val)
  }

  const onTrajectory = async (record: any) => {
    setTrajectoryVisible(true)
    console.log('record', record)
    const { data } = await queryTrajectory({
      serialNo: record.serialNo
    })
    setRecord(record)
    setListData(data)
  }

  const handleInitData = () => {
    //handleGetQueryWaitList({})
  }

  useEffect(() => {
    // handleInitData()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const [visible, setVisible] = useState(false)
  const [modalVisible, setModalVisible] = useState(false)
  // @ts-ignore
  return (
    <div>
      <header>
        <Form validateTrigger="onBlur" form={form} onFinish={onFinish} {...layout}>
          <Row>
            <Col span={12}>
              <Form.Item name="caseNo" label="案件编号：">
                <Input style={{ width: formWidth }} placeholder="请输入案件编号搜索" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="caseName" label="案件名称：">
                <Input style={{ width: formWidth }} placeholder="请输入案件名称搜索" />
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <Form.Item name="informNoteCompanyCode" label="移送/告知单位：">
                <Select
                  showSearch
                  optionFilterProp="children"
                  filterOption={(input, option) => option!.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                  onChange={(value: string) => {
                    setDepartmentCode(value)
                  }}
                  dropdownMatchSelectWidth={false}
                  placeholder="请选择移送/告知单位"
                  style={{ width: formWidth }}
                >
                  {departMents.map((item: any, index: number) => (
                    <Option key={index} value={item.departmentCode}>
                      {item.departmentName}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="informNoteUserNo" label="移送/告知人：">
                <Select placeholder="请选择移送/告知人" style={{ width: formWidth }}>
                  {receiveMembers.map((item: any, index: number) => (
                    <Option key={index} value={item.userNo}>
                      {item.userName}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <Form.Item name="createTime" label="采集时间：">
                <RangePicker style={{ width: formWidth }} showTime={{ format: 'HH:mm' }} format="YYYY-MM-DD HH:mm" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="acquireTime" label="实际执行时间：">
                <RangePicker style={{ width: formWidth }} showTime={{ format: 'HH:mm' }} format="YYYY-MM-DD HH:mm" />
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <Form.Item name="itemName" label="物品名称：">
                <Input style={{ width: formWidth }} placeholder="请输入物品名称搜索" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="acquireWay" label="获取方式：">
                <Select style={{ width: formWidth }}>
                  {[...AcqueryWayMap].map(([key, value], index) => (
                    <Option key={index} value={key}>
                      {value}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <Form.Item name="dealReason" label="处理结果：">
                <Select style={{ width: formWidth }}>
                  {[...TaskItemMap].map(([key, value], index) => (
                    <Option key={index} value={key}>
                      {value}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="storageStatus" label="保管状态：">
                <Select style={{ width: formWidth }}>
                  {[...CustodyState].map(([key, value], index) => (
                    <Option key={index} value={key}>
                      {value}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <Form.Item name="whereabouts" label="物品去向：">
                <Select style={{ width: formWidth }}>
                  {[...WhereaboutsItemsMap].map(([key, value], index) => (
                    <Option key={index} value={key}>
                      {value}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={12}>
              <Form.Item name="itemClassification" label="物品分类">
                <ItemClassification style={{ width: formWidth }} />
              </Form.Item>
            </Col>
          </Row>
          <Row justify={'end'}>
            <Col span={4} style={{ display: 'flex' }}>
              <Form.Item>
                <Button htmlType="submit" type="primary">
                  查询
                </Button>
              </Form.Item>
              <Form.Item>
                <Button
                  onClick={() => {
                    getExcel(moveList)
                  }}
                  style={{ marginLeft: '15px' }}
                >
                  导出
                </Button>
              </Form.Item>
              <Form.Item>
                <Button
                  onClick={() => {
                    console.log('reset')
                    resetFields()
                    // handleInitData()
                  }}
                  style={{ padding: 0, marginLeft: '15px' }}
                  type="link"
                >
                  清空选项
                </Button>
              </Form.Item>
            </Col>
            <Modal footer={null} width={'max-content'} visible={visible}>
              <div
                style={{
                  display: 'flex', // 使用flex布局
                  position: 'absolute', // 绝对定位
                  top: '0px', // 距离父级元素顶部0像素
                  left: '-100px', // 距离父级元素左侧0像素
                  zIndex: 10, // 遮罩层的堆叠层级（只要设置的比被遮罩元素高就行）
                  height: '100px', // 与父级元素同高
                  width: '250px', // 与父级元素同宽
                  background: 'white', // 半透明背景
                  textAlign: 'center',
                  justifyContent: 'space-around',
                  alignItems: 'center'
                }}
              >
                <Spin size={'large'} tip="查询中，请稍候...">
                  {/* <Alert message="Alert message title" description="Further details about the context of this alert." type="info" /> */}
                </Spin>
              </div>

              <ItemModal visible={modalVisible} setVisible={setModalVisible} record={cacheRecord} />
            </Modal>
          </Row>
        </Form>
      </header>
      <main style={{ marginTop: 21 }}>
        <MoveList moveList={moveList} onTrajectory={onTrajectory} />
      </main>
      <TrajectoryModal
        record={record}
        listData={listData}
        visible={trajectoryVisible}
        setVisible={setTrajectoryVisible}
      />
    </div>
  )
}

export default Home
